<?php
/**
 * @package Joomla
 * @subpackage Jmonoslideshow
 * @copyright (C) 2010 - Matthieu BARBE - www.ccomca.com
 * @license GNU/GPL v2
 * 
 * Jmonoslideshow is a Joomla extension for Monoslideshow.
 *
 * Jmonoslideshow uses :
 * Monoslideshow (http://www.monoslideshow.com/)
 * Plupload (http://www.plupload.com/) by Moxicode Systems
 * json class by Michal Migurski, Matt Knapp, Brett Stimmerman
 * jquery a JavaScript Library (http://jquery.com/)
 * getid3 library (http://getid3.sourceforge.net/)
 * swfobject is an easy-to-use and standards-friendly method to embed Flash content, which utilizes one small JavaScript file (http://code.google.com/p/swfobject/)
 * Chained Selects jQuery Plugin (http://www.appelsiini.net/2010/jquery-chained-selects)
 *
 * Jmonoslideshow is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 */

// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );

jimport( 'joomla.application.component.model' );

/**
 * Album Model
 *
 * @package    Jmonoslideshow
 * @subpackage Models
 */
class JmonoslideshowModelCategory extends JModel
{

	/**
	 * Constructor that retrieves the ID from the request
	 *
	 * @access	public
	 * @return	void
	 */
	 
	 var $_lastId = 0;
	 
	function __construct()
	{
		parent::__construct();

		$array = JRequest::getVar('cid',  0, '', 'array');
		$this->setId((int)$array[0]);
	}//function

	/**
	 * Method to set the album identifier
	 *
	 * @access	public
	 * @param	int album identifier
	 * @return	void
	 */
	function setId($id)
	{
		// Set id and wipe data
		$this->_id		= $id;
		$this->_data	= null;
	}//function
	
	function getId()
	{
		//First loooking for new insertion
		if ($this->_lastId > 0) {
			return $this->_lastId ;
		}
		
		$cid = $this->getCid();
		
		if (empty($cid[0])) {
			//try to see id
			return JRequest::getInt('id', 0);
		}
		
		return $cid[0] ;
	}
	
	function getCid()
	{
		$cid = JRequest::getVar( 'cid', array(0), '', 'array' );
		JArrayHelper::toInteger( $cid, array(0) );
		return $cid ;
	}
	
	function &getRow($id)
	{
		$table =& $this->getTable();
		if ($id == null) $cid= $this->getId(); else $cid = $id;
		$table->load( $cid );
		return $table;
	}


	/**
	 * Method to get a record
	 * @return object with data
	 */
	function &getData()
	{
		// Load the data
		if (empty( $this->_data )) {
			$query = ' SELECT * FROM #__monoslideshow_category '.
					'  WHERE id = '.$this->_id;
			$this->_db->setQuery( $query );
			$this->_data = $this->_db->loadObject();
		}
		if (!$this->_data) {
			$this->_data = new stdClass();
			$this->_data->id = 0;
			$this->_data->title = null;
			$this->_data->description = null;
			$this->_data->author = null;
			$this->_data->created = null;
			$this->_data->modified = null;
			$this->_data->modified_by = null;
		}
		return $this->_data;
	}
	
	/**
	 * Method to checkin/unlock 
	 *
	 * @access	public
	 * @return	boolean	True on success
	 * @since	1.5
	 */
	function checkin()
	{
		if ($this->getId())
		{
			$monoslideshow = & $this->getTable();
			if(! $monoslideshow->checkin($this->getId())) {
				$this->setError($this->_db->getErrorMsg());
				return false;
			}
		}
		return false;
	}

	/**
	 * Method to checkout/lock
	 *
	 * @access	public
	 * @param	int	$uid	User ID of the user checking the article out
	 * @return	boolean	True on success
	 * @since	1.5
	 */
	function checkout($uid = null)
	{
		if ($this->getId())
		{
			// Make sure we have a user id to checkout the article with
			if (is_null($uid)) {
				$user	=& JFactory::getUser();
				$uid	= $user->get('id');
			}
			// Lets get to it and checkout the thing...
			$monoslideshow = & $this->getTable();
			if(!$monoslideshow->checkout($uid, $this->getId())) {
				$this->setError($this->_db->getErrorMsg());
				return false;
			}

			return true;
		}
		return false;
	}

	/**
	 * Method to store a record
	 *
	 * @access	public
	 * @return	boolean	True on success
	 */
	function store()
	{
		$row =& $this->getRow();

		 $datas = array(
        	'title'          => JRequest::getVar( 'title', '', 'POST' ),
			'description'    => JRequest::getVar( 'description' , '', 'POST' ),
			'published'   	 => JRequest::getInt( 'published' , 0, 'POST' ),
			'params'   		 => JRequest::getVar( 'params' , '', 'POST', 'array' )
        );

		// Bind the form fields to the hello table
		if (!$row->bind($datas)) {
			$this->setError($this->_db->getErrorMsg());
			return false;
		}

		// Make sure the record is valid
		if (!$row->check()) {
			$this->setError($row->getError());
			return false;
		}
		
	

		// Store the table to the database
		if (!$row->store()) {
			$this->setError( $row->getErrorMsg() );
			return false;
		}
		
		
		$this->_lastId = $row->id;

		return true;
	}//function

	/**
	 * Method to delete record(s)
	 *
	 * @access	public
	 * @return	boolean	True on success
	 */
	function delete()
	{
		$cids = JRequest::getVar( 'cid', array(0), 'post', 'array' );

		$row =& $this->getTable();
		
		jimport('joomla.filesystem.file');
		
		// Set FTP credentials, if given
		jimport('joomla.client.helper');
		JClientHelper::setCredentialsFromRequest('ftp');
		
		if (count( $cids ))
		{
			foreach($cids as $cid) {
				$this->setID($cid);
				$db =& $this->getRow();
				$extension = $db->extension;
				if ($this->checkMedia($cid))
					{
						if (!$row->delete( $cid )) {
							$this->setError( $row->getErrorMsg() );
							return false;
						}
					}
					else
					{
						$this->setError( JText::_('You have of medias in the category') );
						return false;
					}
			}//foreach
		}
		return true;
	}//function
	
	/**
	 * Method to (un)publish 
	 *
	 * @access	public
	 * @return	boolean	True on success
	 * @since	1.5
	 */
	function publish($cid = array(), $publish = 1)
	{
		$user 	=& JFactory::getUser();

		if (count( $cid ))
		{
			JArrayHelper::toInteger($cid);
			$cids = implode( ',', $cid );

			$query = 'UPDATE #__monoslideshow_category'
				. ' SET published = '.(int) $publish
				. ' WHERE id IN ( '.$cids.' )'
				. ' AND ( checked_out = 0 OR ( checked_out = '.(int) $user->get('id').' ) )'
			;
			$this->_db->setQuery( $query );
			if (!$this->_db->query()) {
				$this->setError($this->_db->getErrorMsg());
				return false;
			}
		}

		return true;
	}
	
	
	
	/**
	 * Method to saveorder
	 *
	 * @access	public
	 */
	function saveorder($cid = array(), $order)
	{
		$row =& $this->getTable();
		$groupings = array();

		// update ordering values
		for( $i=0; $i < count($cid); $i++ )
		{
			$row->load( (int) $cid[$i] );
			
			$groupings[] = $row->id;

			if ($row->ordering != $order[$i])
			{
				$row->ordering = $order[$i];
				if (!$row->store()) {
					$this->setError($this->_db->getErrorMsg());
					return false;
				}
			}
		}

		

		return true;
	}
	
	/**
	 * Method to move a media
	 *
	 * @access	public
	 * @return	boolean	True on success
	 * @since	1.5
	 */
	function move($direction)
	{
		$row =& $this->getTable();
		if (!$row->load($this->_id)) {
			$this->setError($this->_db->getErrorMsg());
			return false;
		}

		if (!$row->move( $direction, ' published >= 0 ' )) {
			$this->setError($this->_db->getErrorMsg());
			return false;
		}

		return true;
	}
	
	/**
	 * Method to move a media
	 *
	 * @access	public
	 * @return	boolean	True on success
	 * @since	1.5
	 */
	function checkMedia($cid)
	{
		$db =& JFactory::getDBO();
		$query = 'SELECT c.*, COUNT( m.id ) AS total'
		. ' FROM #__monoslideshow_category AS c'
		. ' LEFT JOIN #__monoslideshow AS m ON m.albumid = c.id'
		. ' WHERE c.id = '.$cid.' '
		. ' GROUP BY c.id'
		;
		$db->setQuery( $query );

		if (!($rows = $db->loadObjectList())) {
			JError::raiseError( 500, $db->stderr() );
			return false;
		}
		
		foreach ($rows as $row) {
			if ($row->total == 0) return true; else return false;
		}
	}

}// class